import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_day_stat.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import '../../../study/main_exam_page.dart';
import '../controller/my_score_recoder_controller.dart';
import 'mine_my_his_recoder_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/4.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
class MineMyScoreRecoderPage extends StatefulWidget {
  const MineMyScoreRecoderPage({
    Key key,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MineItem2State();
  }
}

class _MineItem2State extends State<MineMyScoreRecoderPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  StreamSubscription<String> _streamSubscription;

  //标签页面保活 或者称保持状态
  @override
  bool get wantKeepAlive => true;

  AnimationController _animationController;

  ScrollController _scrollController = new ScrollController();

  MyScoreRecoderController myScoreRecoderController;

  @override
  void initState() {
    super.initState();
    myScoreRecoderController = Get.put(MyScoreRecoderController());
    _animationController = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 1200));

    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      if (offset >= _scrollController.position.maxScrollExtent / 3 * 2) {
        myScoreRecoderController.loadMore();
      }
    });
    Future.delayed(Duration.zero, () {
      myScoreRecoderController.initLoad();
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    if (_streamSubscription != null) {
      _streamSubscription.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return Scaffold(
      appBar: AppBar(
        title: Text("答题记录"),
        actions: [
          buildTopRightActions(),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          await myScoreRecoderController.initLoad();
          ToastUtils.showToast("已刷新");
        },
        child: Container(
          padding: EdgeInsets.only(top: 12),
          color: Colors.white,
          child: GetBuilder(
              id: "root",
              builder: (MyScoreRecoderController controller) {
                return buildAnimatedSwitcher();
              }),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await Get.to(
            () => MainExamPage(),
          );
          await myScoreRecoderController.initLoad();
        },
        child: Text("答题"),
      ),
    );
  }

  buildTopRightActions() {
    return InkWell(
      onTap: () {
        myScoreRecoderController.selectDate(context);
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: 80,
            padding: EdgeInsets.only(left: 4),
            margin: EdgeInsets.only(right: 12),
            height: 26,
            decoration: BoxDecoration(
                border: Border.all(
                  color: Colors.red,
                ),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // Positioned(
                //   left: 0,
                //   child: Image.asset(
                //     "assets/images/2.0x/book_tips.gif",
                //     width: 42,
                //   ),
                // ),
                Positioned(
                  right: 12,
                  child: Container(
                    child: GetBuilder(
                        id: "selectTimes",
                        builder: (MyScoreRecoderController controller) {
                          return Text(
                            controller.myScoreCurrentSelectDate,
                            style: TextStyle(color: Colors.red),
                          );
                        }),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  AnimatedSwitcher buildAnimatedSwitcher() {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 400),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },

      //执行动画的子 Widget
      //只有子 Widget 被切换时才会触发动画
      child: buildBody(),
    );
  }

  Widget buildBody() {
    List<BeanDayStat> getDayStatList =
        myScoreRecoderController.getDayStatList();
    bool _loading = myScoreRecoderController.getIsLoading();
    if (getDayStatList.length == 0) {
      if (_loading) {
        return Center(
          child: LoadingWidget(),
        );
      }
      return Container(
        child: NoDataWidget(
          text: "暂无数据",
        ),
      );
    }
    return Container(
      color: Color(0xfff7f7f7),
      child: ListView.builder(
        controller: _scrollController,
        //去除内边距
        padding: EdgeInsets.all(0),
        //列表子Item个数
        itemCount: getDayStatList.length,
        //每个子Item的布局构建
        itemBuilder: (BuildContext context, int index) {
          return buildBodyWidget(index, getDayStatList);
        },
      ),
    );
  }

  //每个子Item的布局构建
  Widget buildBodyWidget(int index, List<BeanDayStat> getDayStatList) {
    BeanDayStat beanDayStat = getDayStatList[index];
    String timeStr = "${beanDayStat.answerTime}秒";
    if (beanDayStat.answerTime <= 0) {
      timeStr = '--';
    }
    if (beanDayStat.answerTime > 60) {
      timeStr =
          "${beanDayStat.answerTime ~/ 60}分${(beanDayStat.answerTime % 60).toInt()}秒";
    }

    double obtainScore = beanDayStat.obtainScore / 10 / beanDayStat.extryScore;

    return InkWell(
      onTap: () {
        if (beanDayStat.extractingId == null) {
          return;
        }
        NavigatorUtils.pushPage(
          context,
          MineMyScoreHisRecoderPage(
            extractingId: beanDayStat.extractingId ?? 0,
          ),
        );
      },
      child: Container(
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.all(10),
        color: Colors.white,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 2,
              height: 14,
              margin: EdgeInsets.only(left: 10, right: 8, top: 6),
              color: Colors.blue,
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Text(
                        "考试时间",
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        beanDayStat.createTime ?? '',
                        style: TextStyle(
                          fontSize: 14,
                        ),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Row(
                    children: [
                      Text(
                        "答题时间",
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        timeStr,
                        style: TextStyle(
                          fontSize: 12,
                        ),
                      ),
                      SizedBox(
                        width: 30,
                      ),
                      Text(
                        "得分",
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "${obtainScore.toStringAsFixed(2)}分",
                        style: TextStyle(
                          fontSize: 12,
                        ),
                      )
                    ],
                  ),
                  buildIntegerScoreContainer(beanDayStat),
                ],
              ),
            ),
            Container(
              child: Icon(
                Icons.arrow_forward_ios,
                size: 12,
              ),
              margin: EdgeInsets.only(top: 6),
            )
          ],
        ),
      ),
    );
  }

  Widget buildIntegerScoreContainer(BeanDayStat beanDayStat) {
    if (beanDayStat.integerRemark.isEmpty) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: Text(
        "积分${beanDayStat.integerScore}分； ${beanDayStat.integerRemark}",
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey,
        ),
      ),
    );
  }
}
